package ui.swing.textcomponent.fmt;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DateFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JToggleButton;
import javax.swing.border.EmptyBorder;

public class FTFDemo extends JFrame implements ActionListener{

	private static final long serialVersionUID = -3376159139835742326L;

	JFormattedTextField ftfDate = new JFormattedTextField();
	
	public FTFDemo() {
		super("Formatted TextField");
		
		JPanel main = new JPanel(); //(new DialogLayout2());
		main.setBorder(new EmptyBorder(10, 10, 10, 10));
		
		main.add(new JLabel("Dollar amount:"));
		NumberFormat formatMoney = NumberFormat.getCurrencyInstance(Locale.US);
		JFormattedTextField ftMoney = new JFormattedTextField(formatMoney);
		ftMoney.setColumns(10);
		ftMoney.setValue(new Double(100));
		main.add(ftMoney);
		
		main.add(new JLabel("Transaction date:"));
		DateFormat formatDate = new SimpleDateFormat("MM/dd/yyyy");
		ftfDate = new JFormattedTextField(formatDate);
		ftfDate.setColumns(10);
		ftfDate.setValue(new Date());
		main.add(ftfDate);
		
		JButton btn = new JButton("OK");
		main.add(btn);
		JPanel btnPanel = new JPanel();
		JToggleButton btn0 = new JToggleButton("COMMIT");
		JToggleButton btn1 = new JToggleButton("COMMIT_OR_REVERT");
		JToggleButton btn2 = new JToggleButton("REVERT");
		JToggleButton btn3 = new JToggleButton("PERSIST");
		btn0.addActionListener(this);
		btn1.addActionListener(this);
		btn2.addActionListener(this);
		btn3.addActionListener(this);
		ButtonGroup bg = new ButtonGroup();
		bg.add(btn0);
		bg.add(btn1);
		bg.add(btn2);
		bg.add(btn3);
		btnPanel.add(btn0);
		btnPanel.add(btn1);
		btnPanel.add(btn2);
		btnPanel.add(btn3);
		btn3.setSelected(true);
		
		getContentPane().add(main, BorderLayout.CENTER);
		getContentPane().add(btnPanel, BorderLayout.SOUTH);
		pack();
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		setVisible(true);
	}
	
	
	
	public static void main(String[] args) {
		new FTFDemo();
	}

	public void actionPerformed(ActionEvent e) {
		if("COMMIT".equals(e.getActionCommand())) {
			ftfDate.setFocusLostBehavior(JFormattedTextField.COMMIT);
			return;
		}
		if("COMMIT_OR_REVERT".equals(e.getActionCommand())) {
			ftfDate.setFocusLostBehavior(JFormattedTextField.COMMIT_OR_REVERT);		
			return;	
		}
		if("REVERT".equals(e.getActionCommand())) {
			ftfDate.setFocusLostBehavior(JFormattedTextField.REVERT);		
			return;	
		}
		if("PERSIST".equals(e.getActionCommand())) {
			ftfDate.setFocusLostBehavior(JFormattedTextField.PERSIST);
			return;
		}
	}
	
}
